<template>
  <div style="padding: 30px; width: 940px">
    <el-form ref="teamMemberFormRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职务" prop="position">
            <el-input v-model="form.position" placeholder="请输入职务" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number style="width: 100%" v-model="form.sort" :min="1" placeholder="默认自动累加顺序号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对外展示" prop="visible">
            <el-switch :active-value="1" :inactive-value="0" v-model="form.visible" inline-prompt :active-icon="Check" :inactive-icon="Close" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :rules="{ required: form.visible == 1, message: '请上传头像', trigger: 'change' }" label="头像" prop="avatar">
        <image-upload v-model="form.avatar" :limit="1" />
      </el-form-item>
      <el-form-item label="简介">
        <div :class="{'ueditor-dark': isDark}">
          <vue-ueditor-wrap
            style="min-width: 880px; width: 880px"
            v-model="form.intro"
            :editor-id="editorId"
            :config="editorConfig"
            :editor-dependencies="['ueditor.config.js', 'ueditor.all.js']"
            @ready="handleEditorReady"
          />
        </div>
      </el-form-item>
    </el-form>
    <div style="text-align: center; width: 880px" class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import router from '@/router';
import { listTeamMember, getTeamMember, delTeamMember, addTeamMember, updateTeamMember } from '@/api/business/teamMember';
import { TeamMemberVO, TeamMemberQuery, TeamMemberForm } from '@/api/business/teamMember/types';
import { Check, Close } from '@element-plus/icons-vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ywsf } = toRefs<any>(proxy?.useDict('ywsf'));
const route = useRoute();
const buttonLoading = ref(false);
const teamMemberFormRef = ref<ElFormInstance>();
const editorId = ref(null);
import { globalHeaders } from '@/utils/request';
import { computed } from 'vue';
import { useDark } from '@vueuse/core';
import { useUEditorDarkMode, extendUEditorConfig } from '@/utils/ueditor';
import { onBeforeUnmount } from 'vue';

// 基础编辑器配置
const editorConfigBase = {
  // 后端服务地址，后端处理参考
  // https://open-doc.modstart.com/ueditor-plus/backend.html
  serverUrl: import.meta.env.VITE_APP_BASE_API + '/ueditor/exec',
  serverHeaders: globalHeaders(),
  initialFrameWidth: 800,
  initialFrameHeight: 400,
  autoHeightEnabled: false,
  UEDITOR_HOME_URL: import.meta.env.VITE_APP_CONTEXT_PATH + '/static/UEditorPlus/',
  UEDITOR_CORS_URL: import.meta.env.VITE_APP_CONTEXT_PATH + '/static/UEditorPlus/'
};

// 使用扩展的编辑器配置
const editorConfig = computed(() => {
  try {
    return extendUEditorConfig(editorConfigBase);
  } catch (error) {
    console.warn('扩展编辑器配置失败，使用基础配置', error);
    return {
      ...editorConfigBase,
      enableDarkMode: isDark.value
    };
  }
});

// 存储暗黑模式处理对象
let ueditorDarkMode: ReturnType<typeof useUEditorDarkMode> | null = null;

// 是否暗黑模式
const isDark = useDark({
  storageKey: 'useDarkKey',
  valueDark: 'dark',
  valueLight: 'light'
});

const initFormData: TeamMemberForm = {
  baseId: undefined,
  type: route.query.type,
  name: undefined,
  position: undefined,
  avatar: undefined,
  intro: undefined,
  sort: undefined,
  visible: undefined
};
const data = reactive<PageData<TeamMemberForm, TeamMemberQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: route.query.type,
    name: undefined,
    position: undefined,
    avatar: undefined,
    intro: undefined,
    sort: undefined,
    visible: undefined,
    params: {}
  },
  rules: {
    baseId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    position: [{ required: true, message: '职务不能为空', trigger: 'blur' }],
    intro: [{ required: true, message: '简介不能为空', trigger: 'blur' }],
    visible: [{ required: true, message: '审核不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
/** 取消按钮 */
const cancel = () => {
  reset();
  proxy?.$tab.closePage();
};

/** 表单重置 */
const reset = () => {
  form.value = {
    ...initFormData
  };
  teamMemberFormRef.value?.resetFields();
};
/** 提交按钮 */
const submitForm = () => {
  teamMemberFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.type = proxy.$route.query.type;
      if (form.value.baseId) {
        await updateTeamMember(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTeamMember(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      cancel();
    }
  });
};
onMounted(async () => {
  editorId.value = 'editorId' + Math.floor(Math.random() * 100);
  
  // 初始化UEditor暗黑模式支持
  try {
    ueditorDarkMode = useUEditorDarkMode(editorId);
    ueditorDarkMode.initialize();
  } catch (error) {
    console.warn('初始化UEditor暗黑模式失败，将使用默认模式', error);
  }
  
  if (proxy.$route.query.id) {
    const res = await getTeamMember(proxy.$route.query.id);
    Object.assign(form.value, res.data);
  }
});

// 编辑器初始化完成回调
const handleEditorReady = () => {
  // 编辑器初始化完成后手动应用暗黑模式
  if (ueditorDarkMode) {
    try {
      ueditorDarkMode.applyDarkModeManually();
    } catch (error) {
      console.warn('应用暗黑模式到编辑器失败', error);
    }
  }
};

// 组件卸载时清理资源
onBeforeUnmount(() => {
  if (ueditorDarkMode) {
    try {
      ueditorDarkMode.cleanup();
    } catch (error) {
      console.warn('清理UEditor暗黑模式失败', error);
    }
  }
});
</script>

<style lang="scss" scoped>
.ueditor-dark {
  :deep(.edui-default .edui-editor) {
    border-color: #444;
    background-color: #1e1e1e;
  }
  
  :deep(.edui-default .edui-editor-toolbarboxouter) {
    background-color: #333;
    border-bottom-color: #444;
  }
  
  :deep(.edui-default .edui-toolbar .edui-button .edui-state-hover .edui-button-wrap) {
    background-color: #444;
    border-color: #555;
  }
  
  :deep(.edui-default .edui-toolbar .edui-button .edui-state-checked .edui-button-wrap) {
    background-color: #444;
    border-color: #555;
  }
  
  /* 确保编辑区域容器样式 */
  :deep(.edui-default .edui-editor-iframeholder) {
    background-color: #fff;
    border-color: #444;
  }
  
  /* 下拉菜单样式 */
  :deep(.edui-default .edui-dropdown-menu) {
    background-color: #333;
    border-color: #444;
  }
  
  :deep(.edui-default .edui-dropdown-menu .edui-combobox-item) {
    color: #ddd;
  }
  
  :deep(.edui-default .edui-dropdown-menu .edui-combobox-item-hover) {
    background-color: #444;
  }
  
  /* 工具栏内的选择框和文本框 */
  :deep(.edui-default .edui-toolbar .edui-combox),
  :deep(.edui-default .edui-toolbar .edui-menubutton),
  :deep(.edui-default .edui-toolbar .edui-splitbutton),
  :deep(.edui-default .edui-toolbar .edui-combox .edui-button-body),
  :deep(.edui-default .edui-toolbar .edui-menubutton .edui-button-body),
  :deep(.edui-default .edui-toolbar .edui-splitbutton .edui-button-body) {
    background-color: #333 !important;
    border-color: #555 !important;
    color: #ddd !important;
  }
  
  /* 下拉按钮箭头 */
  :deep(.edui-default .edui-toolbar .edui-arrow) {
    background-color: #333 !important;
  }
  
  /* 下拉菜单按钮文本 */
  :deep(.edui-default .edui-toolbar .edui-combox .edui-button-body .edui-label),
  :deep(.edui-default .edui-toolbar .edui-menubutton .edui-button-body .edui-label),
  :deep(.edui-default .edui-toolbar .edui-splitbutton .edui-button-body .edui-label) {
    color: #ddd !important;
  }
}
</style>
